package rpc.server.netty;

import rpc.common.enumeraion.PackageType;
import rpc.intf.ServiceProvider;
import rpc.intf.impl.DefaultServiceProvider;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import rpc.packet.RpcMessage;
import rpc.packet.RpcRequest;
import rpc.packet.RpcResponse;
import rpc.server.RequestHandler;

@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler {

    private static RequestHandler requestHandler;
    public static ServiceProvider serviceProvider;

    static {
        requestHandler = new RequestHandler();
        serviceProvider = new DefaultServiceProvider();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        log.debug("服务器接收到请求: {}", msg);

        if (msg instanceof RpcMessage) {
            RpcMessage rpcMessage = (RpcMessage) msg;

            if (rpcMessage.getPackageType() == PackageType.REQUEST_PACK.getCode()) {
                RpcRequest rpcRequest = (RpcRequest) rpcMessage.getData();

                String interfaceName = rpcRequest.getInterfaceName();
                Object service = serviceProvider.getService(interfaceName);

                Object result = requestHandler.handle(rpcRequest, service);

                log.debug("远程调用结果: {}", result);

                rpcMessage.setPackageType(PackageType.RESPONSE_PACK.getCode());
                rpcMessage.setData(RpcResponse.success(result, rpcRequest.getRequestId()));
                rpcMessage.setRequestId(rpcRequest.getRequestId());

                ChannelFuture future = ctx.writeAndFlush(rpcMessage);
                future.addListener(ChannelFutureListener.CLOSE);
            }
        }


    }
}
